<template>
  <!-- <div class="container" style="width: 100%; height: 100%;"> -->
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span class="active">缴费</span>
    </div>

    <el-row>
      <!-- 搜索部分 -->
      <el-col :span="24">
        <el-form :inline="true" :model="query" class="demo-form-inline" ref="queryForm">
          <el-form-item label="状态">
            <el-select style="width: 100px;" v-model="query.state" clearable>
              <el-option label="未缴费" :value="1"></el-option>
              <el-option label="已缴费" :value="2"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="账期">
            <el-date-picker
             style="width: 200px;"
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item label="楼栋">
            <CasCader style="width: 200px;" @handleChange="handleChange"></CasCader>
          </el-form-item>
          
          <el-form-item label="房号">
            <el-input style="width: 120px;" v-model="query.houseno"  clearable></el-input>
          </el-form-item>
          
          <el-form-item label="姓名">
            <el-input style="width: 120px;" v-model="query.userName"  clearable></el-input>
          </el-form-item>
          
          <el-form-item label="电话">
            <el-input style="width: 120px;" v-model="query.mobile"  clearable></el-input>
          </el-form-item>
          
          <el-form-item label="添加人">
            <el-input style="width: 180px;" v-model="query.admin"  clearable></el-input>
          </el-form-item>
          
          <el-form-item label="流水账单">
            <el-input style="width: 180px;" v-model="query.orderno"  clearable></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="btns">
      <el-button type="primary" @click="handleAddFee">添加</el-button>
      <el-button type="primary" class="ico" size="small" @click="handleDeleteAll">批量删除</el-button>
    </el-row>

    <!--  表格 -->

    <BaseTable
      :tableColumn="tableColumn"
      :tableData="tableData"
      :loading="loading"
      @edit="handleClick"
      @delete="handleDelete"
      :isShowSelection="isShowSelection"
      @selection-change="handleSelectionChange"
    >
      <template #options="{ row }">
        <el-button @click="handleViewDetails(row)" type="success" size="mini">详情</el-button>
        <el-button size="mini" @click="handleDelete(row)" type="danger">删除</el-button>
      </template>
    </BaseTable>

    <!-- 分页 -->
    <el-pagination 
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.page"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="query.psize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="counts"
    >
    </el-pagination>

    <!-- 添加/编辑弹窗 -->
    <DialogHouse :dialogVisible="dialogVisible" :isEdit="isEdit" :editData="editData" @handleCancel="handleCancel" @refreshList="refreshList">
    </DialogHouse>
    
    <!-- 添加费用弹窗 -->
    <el-dialog title="添加费用" :visible.sync="addFeeDialogVisible" width="50%" @close="handleAddFeeDialogClose">
      <el-form size="mini" :model="feeForm" :rules="feeFormRules" ref="feeForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="费用类型" prop="type">
          <el-select v-model="feeForm.type" placeholder="请选择费用类型" style="width: 200px;">
            <el-option label="物业费" value="物业费"></el-option>
            <el-option label="水电费" value="水电费"></el-option>
            <el-option label="停车费" value="停车费"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="金额" prop="price">
          <el-input class="elinput" v-model.number="feeForm.price" type="number" placeholder="请输入金额"></el-input>
        </el-form-item>
        
        <el-form-item label="账期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="小区" prop="buildingid">
          <el-cascader
            size="small"
            :value="buildingValue"
            :options="buildingOptions"
            @change="handleBuildingChange"
            :props="{ value: 'id', label: 'name' }"
            clearable
            style="width: 200px;">
          </el-cascader>
        </el-form-item>
        
        <el-form-item label="房间选择">
          <el-radio-group v-model="roomSelectionType" @change="handleRoomSelectionTypeChange">
            <el-radio :label="1">全部</el-radio>
            <el-radio :label="2">部分房间</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="roomSelectionType === 2" label="选择房间" prop="houseids">
          <el-select v-model="feeForm.houseids" multiple placeholder="请选择房间" style="width: 200px;">
            <el-option
              v-for="item in houseList"
              :key="item.id"
              :label="item.houseno"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddFeeDialogClose">取 消</el-button>
        <el-button type="primary" @click="submitFeeForm">确 定</el-button>
      </span>
    </el-dialog>
    
    <!-- 费用详情弹窗 -->
    <el-dialog title="费用详情" :visible.sync="detailDialogVisible" width="50%" @close="handleDetailDialogClose">
      <el-form size="mini" :model="detailForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="费用类型">
          <span>{{ detailForm.type }}</span>
        </el-form-item>
        
        <el-form-item label="金额">
          <span>{{ detailForm.price }}</span>
        </el-form-item>
        
        <el-form-item label="账期">
          <span>{{ detailForm.begindate }} 至 {{ detailForm.enddate }}</span>
        </el-form-item>
        
        <el-form-item label="小区">
          <span>{{ detailForm.buildingName }}</span>
        </el-form-item>
        
        <el-form-item label="房间信息">
          <span>{{ detailForm.houseInfo }}</span>
        </el-form-item>
        
        <el-form-item label="状态">
          <span>{{ detailForm.stateName }}</span>
        </el-form-item>
        
        <el-form-item label="添加时间">
          <span>{{ detailForm.addtime }}</span>
        </el-form-item>
        
        <el-form-item label="添加人">
          <span>{{ detailForm.admin }}</span>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleDetailDialogClose">关 闭</el-button>
      </span>
    </el-dialog>
  </el-card>
  <!-- </div> -->
</template>

<script>
import CasCader from '../components/CasCader.vue';
import DialogHouse from '../components/DialogHouse.vue'
import { list, delAll, del } from '../api/fee'
import BaseTable from '@/components/BaseTable.vue'
import { miXinPower } from '@/utils/miXinPower.js'
// 引入需要用到的API
import { list as getBuildingList } from '@/api/building'
import { houseslist } from '@/api/administrator'
import { add } from '@/api/fee'

export default {
  name: 'FeeView',
  components: {
    CasCader,
    DialogHouse,
    BaseTable
  },
  mixins: [miXinPower],
  data() {
    return {
      dialogVisible: false,
      addFeeDialogVisible: false,
      isEdit: false,
      editData: {},
      orientationDat: ['朝南', '朝东', '朝北', '朝西'],
      loading: true,
      query: {
        page: 1,
        psize: 5,
        key: '',
        type: '',
        state: null,
        begindate: '',
        enddate: '',
        buildingid: '',
        houseno: '',
        userName: '',
        mobile: '',
        admin: '',
        orderno: ''
      },
      dateRange: [],
      buildingValue: [],
      buildingOptions: [],
      houseList: [],
      roomSelectionType: 1, // 1: 全部, 2: 部分房间
      feeForm: {
        type: '',
        begindate: '',
        enddate: '',
        price: '',
        buildingid: '',
        houseids: []
      },
      feeFormRules: {
        type: [{ required: true, message: '请选择费用类型', trigger: 'change' }],
        price: [
          { required: true, message: '请输入应缴金额', trigger: 'blur' },
          { type: 'number', message: '金额必须为数字值', trigger: 'blur' }
        ],
        buildingid: [{ required: true, message: '请选择小区', trigger: 'change' }]
      },
      
      // 费用详情相关数据
      detailDialogVisible: false,
      detailForm: {
        id: '',
        type: '',
        begindate: '',
        enddate: '',
        price: '',
        buildingid: '',
        buildingName: '',
        houseInfo: '',
        stateName: '',
        addtime: '',
        admin: ''
      },
      isShowSelection: true,
      counts: 0,
      selectedRows: [],
      tableColumn: [
        {
          prop: 'building',
          label: '楼号号',
          width: 180,
        },
        {
          prop: 'houseno',
          label: '房间号',
        },
        {
          prop: 'userName',
          label: '姓名',
        },
        {
          prop: 'mobile',
          label: '联系方式',
        },
        {
          prop: 'type',
          label: '缴费类型',
        },
        {
          prop: 'begindate',
          label: '账期',
        },
        {
          prop: 'price',
          label: '应缴金源',
        },
        {
          prop: 'stateName',
          label: '状态',
        },
        {
          prop: 'addtime',
          label: '导入时间',
        },
        {
          prop: 'admin',
          label: '添加人',
        },
        {
          prop: 'options',
          label: '操作',
          slotname: 'options',
        },
      ],
      gridData: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: '',
      },
      formLabelWidth: '120px',

      currentPage1: 5,
      currentPage2: 5,
      currentPage3: 5,
      currentPage4: 4,
      formInline: {
        user: '',
        region: '',
      },
      tableData: [],
      multipleSelection: [],
    }
  },

  methods: {
    handleAdd() {
      this.isEdit = false
      this.dialogVisible = true
    },
    
    handleAddFee() {
      this.addFeeDialogVisible = true
      // 获取楼栋列表
      this.getBuildingList()
    },

    refreshList() {
      this.dialogVisible = false
      this.isEdit = false
      this.getList()
    },

    handleCancel() {
      this.dialogVisible = false
      this.isEdit = false
    },
    
    handleAddFeeDialogClose() {
      this.addFeeDialogVisible = false
      this.resetFeeForm()
    },
    
    handleChange(buildingarr) {
      this.query.buildingid = buildingarr.length ? buildingarr[buildingarr.length - 1] : ''
    },
    
    // 查看详情
    handleViewDetails(row) {
      this.detailDialogVisible = true;
      
      // 填充详情表单数据
      this.detailForm = {
        id: row.id,
        type: row.type,
        begindate: row.begindate,
        enddate: row.enddate,
        price: row.price,
        buildingid: row.buildingid,
        buildingName: row.building,
        houseInfo: row.houseno ? `房号: ${row.houseno}` : '全部房间',
        stateName: row.stateName,
        addtime: row.addtime,
        admin: row.admin
      };
    },
    
    handleSelectionChange(selectedRows) {
      this.selectedRows = selectedRows
    },
    
    handleDeleteAll() {
      if (!this.selectedRows.length) return this.$message.error('请选择要删除的记录')
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          let ids = this.selectedRows.map((item) => item.id)
          await delAll({ ids: ids })
          await this.getList()
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    
    handleDelete(row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await del({ id: row.id })
          await this.getList()
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    
    // 详情对话框关闭
    handleDetailDialogClose() {
      this.detailDialogVisible = false;
    },

    handleClick() {},

    async getList() {
      this.loading = true
      try {
        // 处理日期范围
        if (this.dateRange && this.dateRange.length === 2) {
          this.query.begindate = this.dateRange[0]
          this.query.enddate = this.dateRange[1]
        } else {
          this.query.begindate = ''
          this.query.enddate = ''
        }
        
        let {
          data: { counts, list: listData },
        } = await list(this.query)
        this.counts = counts
        this.tableData = listData
        this.loading = false
      } catch (error) {
        console.error('获取数据失败:', error)
        this.loading = false
      }
    },
    
    onSubmit() {},
    
    handleSizeChange(val) {
      this.query.psize = val
      this.query.page = 1
      this.getList()
    },
    
    handleCurrentChange(val) {
      this.query.page = val
      this.getList()
    },
    
    search() {
      this.query.page = 1
      this.getList()
    },
    
    // 重置查询条件
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.dateRange = []
      this.query.buildingid = ''
      this.query.page = 1
      this.getList()
    },

    // 获取楼栋列表
    async getBuildingList() {
      try {
        const res = await getBuildingList({})
        this.buildingOptions = res.data.list || []
      } catch (error) {
        console.error('获取楼栋列表失败:', error)
        this.$message.error('获取楼栋列表失败!')
      }
    },

    // 获取房间列表
    async getHouseList(buildingid) {
      try {
        const res = await houseslist({ buildingid })
        this.houseList = res.data.list || []
      } catch (error) {
        console.error('获取房间列表失败:', error)
        this.$message.error('获取房间列表失败!')
      }
    },

    // 楼栋选择变化
    handleBuildingChange(value) {
      this.buildingValue = value
      // 获取楼栋ID（取最后一级）
      this.feeForm.buildingid = value && value.length ? value[value.length - 1] : ''
      this.feeForm.houseids = []
      this.houseList = [] // 清空房间列表

      // 获取选中楼栋下的房间列表
      if (this.feeForm.buildingid) {
        this.getHouseList(this.feeForm.buildingid)
      }
    },

    // 房间选择类型变化
    handleRoomSelectionTypeChange(val) {
      if (val === 1) {
        // 选择全部时，清空已选择的房间
        this.feeForm.houseids = []
      }
    },

    // 添加费用表单提交
    async submitFeeForm() {
      this.$refs.feeForm.validate(async (valid) => {
        if (valid) {
          try {
            // 设置账期开始和结束日期
            if (this.dateRange && this.dateRange.length === 2) {
              this.feeForm.begindate = this.dateRange[0]
              this.feeForm.enddate = this.dateRange[1]
            } else {
              return this.$message.error('请选择账期!')
            }

            // 如果选择全部房间，则传空数组表示所有房间
            if (this.roomSelectionType === 1) {
              this.feeForm.houseids = []
            }

            await add(this.feeForm)
            this.$message.success('添加成功!')
            this.addFeeDialogVisible = false
            this.resetFeeForm()
            this.getList()
          } catch (error) {
            this.$message.error('添加失败!')
            console.error('添加费用失败:', error)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 重置添加费用表单
    resetFeeForm() {
      this.$refs.feeForm.resetFields()
      this.dateRange = []
      this.buildingValue = []
      this.houseList = []
      this.roomSelectionType = 1 // 默认选择全部
    }
  },

  created() {
    this.getList()
  },
}
</script>

<style lang="less" scoped>
@import url(../assets/css/search.less);

.ico {
  height: 40px;
  background-color: #f56c6c;
}
</style>